<?php

namespace App\Http\Model;

use Illuminate\Database\Eloquent\HasCollection;
use Illuminate\Support\Facades\DB;
use Ramsey\Uuid\Uuid;
use Illuminate\Database\Eloquent\Model;

class BasicModel extends Model
{
    use HasCollection;

    protected $connection = 'mysql';
    public $timestamps = false;

    protected $attributes = [
        'id' => 0,
        'code' => '',
        'sort' => 0,
        'status' => 1,
        'version' => 0,
        'aTime' => 0,
        'uTime' => 0,
        'dTime' => 0,
        'ip' =>'',
        'os' => '',
    ];

    private function getBasicData(): array
    {
        return [
            "uTime"=>getTotalMillisecond(),
            "ip"=>getClientIp(),
            "os"=>getClientBrowser(),
        ];
    }

    public function getCode() : string
    {
        return Uuid::uuid7()->toString();
    }

    public function getArray(array $where = array())
    {
        $model = $this;
        $defaultWhere = [
            [ 'deleted', "=", 0],
            [ 'status', "=", 1],
        ];
        if (!empty($where)) {
            $defaultWhere = array_merge($defaultWhere, $where);
        }
        return $model->where($defaultWhere)->get()->toArray();
    }

    public function createInfo(array $create = array())
    {
        $basicData = [
            "code"=>$this->getTable() . getTotalMillisecond(),
            "cTime"=>getTotalMillisecond(),
            "version"=> 0,
        ];
        return $this->insertGetId(array_merge($this->getBasicData(), $basicData, $create));
    }

    public function deleteInfo(array $where = array(), array $actionUser = array(), string $inField = "", array $inData = array())
    {
        $defaultUpdate = [
            "deleted"=>1,
            "dTime"=>getTotalMillisecond(),
            "version"=> DB::raw("version + 1"),
        ];
        $model = $this;
        if ($inField && !empty($inData)) {
            $model = $model->whereIn($inField, $inData);
        }
        if (!empty($where)) {
            $model = $model->where($where);
        }
        return $model->update(array_merge($this->getBasicData(), $defaultUpdate, $actionUser));
    }

    public function updateInfo(array $where = array(), array $update = array(), string $inField = "", array $inData = array())
    {
        $defaultUpdate = [
            "version"=> DB::raw("version + 1"),
        ];
        $model = $this;
        if ($inField && !empty($inData)) {
            $model = $model->whereIn($inField, $inData);
        }
        if (!empty($where)) {
            $model = $model->where($where);
        }
        return $model->update(array_merge($this->getBasicData(), $defaultUpdate, $update));
    }

    public function hasData(array $where = array()): bool
    {
        return $this->where($where)->count() > 0;
    }
}
